package v1

import (
	"github.com/gin-gonic/gin"
	"main/middlewares/public/cache"
	"main/middlewares/public/jwt"
	"main/middlewares/public/status"
	"main/middlewares/public/util"
	"main/models"
	"strconv"
)

// @Summary 获取用户应用列表
// @Description  应用列表
// @Tags 权限
// @Produce  json
// @Param   token       header    string  true       "JWT令牌"
// @Success 200  {object} models.H_service
// @Failure 201
// @router /api/v1/GetAuth/ [get]
func GetServiceList(c *gin.Context) {
	claims := c.MustGet("claims").(*jwt.CustomClaims)
	CacheKey := strconv.Itoa(claims.Id)
	CacheKey = CacheKey+"_services"

	if services := cache.Gmaps.Get(CacheKey) ; services!=nil{
		util.SuccessResponse(c,services)
		return
	}
	var license = models.H_license {
		User_id:claims.Id,
		Company_id:claims.Company_id,
	}
	Licenses,err := license.GetLicenses()
	if  err !=nil{
		util.FailedResponse(c,status.DefaultError,err.Error())
		return
	}
	ids := make([]int,0)
	for _,val := range Licenses{
		ids = append(ids, val.Service_id)
	}
	if(len(ids)==0){
		util.FailedResponse(c,status.DefaultError,"获取应用列表错误2")
		return
	}
	services,err := models.GetServices(ids)
	if  err !=nil{
		util.FailedResponse(c,status.DefaultError,err.Error())
		return
	}
	cache.Gmaps.Set(CacheKey,services)
	util.SuccessResponse(c,services)
	return
}

// @Summary 应用鉴权
// @Description  鉴定用户是否有使用此应用的权限
// @Tags 权限
// @Produce  json
// @Success 200  {object} models.H_service
// @Param   id       path    string  true       "应用ID"
// @Param   token       header    string  true       "JWT令牌"
// @Failure 201
// @router /api/v1/GetAuth/{id} [get]
func AuthService(c *gin.Context)  {
 	claims := c.MustGet("claims").(*jwt.CustomClaims)
	serviceID := c.Param("id")
	var HLicense  = models.H_license{
		Company_id:            claims.Company_id,
		User_id:               claims.Id,
	}
	var where = make(map[string]interface{})
	where["service_id"] = serviceID
	license,err := HLicense.GetLicense(where)
	if err !=nil{
		util.FailedResponse(c,status.DefaultError,err.Error())
		return
	}
	if license.IsEmpty(){
		util.FailedResponse(c,status.DefaultError,"无权访问")
		return
	}
	util.SuccessResponse(c, nil)

}

// @Summary 删除应用列表缓存
// @Description  删除指定用户应用列表缓存
// @Tags 权限
// @Produce  json
// @Success 200  {object} models.H_service
// @Param   id       path    string  true       "用户名"
// @Failure 201
// @router /api/v1/GetAuth/{id} [delete]
func DelServiceCache(c *gin.Context)  {
	CacheKey := c.Param("id")
	CacheKey = CacheKey+"_services"
	cache.Gmaps.Remove(CacheKey)
	util.SuccessResponse(c, nil)
}
